package com.vcs.frm.dao.client;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.vcs.frm.domain.Client;
import com.vcs.frm.domain.Company;
import com.vcs.frm.domain.Job;
import com.vcs.frm.domain.User;
import com.vcs.frm.domain.UserRole;
import com.vcs.frm.utils.Constants;

@Repository
public class ClientDaoImpl implements ClientDao {

	/* Logger object */
	private final Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public void registerClient(Client client, User user) {
		Session session = sessionFactory.getCurrentSession();

		// user
		user.setEnabled(1);
		Long userId = (Long) session.save(user);
		session.save(user);
		// user role
		UserRole role = new UserRole(userId, Constants.ROLE_CLIENT);
		session.save(role);
		// company
		Company company = (Company) session.get(Company.class, 1L);
		
		client.setId(userId);
		//client.setCompany(company);	
		Long id = (Long) session.save(client);
		System.out.println("Client registred with : " + id);

	}

	@Override
	public Client getClientProfileById(Long clientId) {

		Client c = null;
		Session session = sessionFactory.getCurrentSession();
		c = (Client) session.get(Client.class, clientId);
		log.info("Client has " + c.getJobs().size() + " Jobs and Company is : "+ c +".");
		return c;
	}

	@Override
	public void postNewJob(Job job) {

		Session session = sessionFactory.getCurrentSession();
		// session.merge(job);
		session.save(job);
	}

	@Override
	public List<Job> getJobsPostedByClient(Long clientId) {

		Session session = sessionFactory.getCurrentSession();
		String qry = "from Job j where j.client.id = :clientId order by j.createdDate desc";

		Query query = session.createQuery(qry).setLong("clientId", clientId);

		@SuppressWarnings("unchecked")
		List<Job> jobs = (List<Job>) query.list();
		int size = jobs.size();
		log.info(size + " jobs found");
		return jobs;
	}

}
